package com.ysjy.course.controller;

import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.utils.StringUtil;
import com.ysjy.course.model.*;
import com.ysjy.course.service.CourseService;
import com.ysjy.course.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(description = "订单管理")
@RequestMapping("/order/manage")
@Slf4j
public class OrderManageController extends BaseController {

    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "学生缴费信息（订单列表）")
    @RequestMapping(value = "getOrderListByStudent", method = RequestMethod.GET)
    public ResultDTO<List<YsOrder>> getOrderListByStudent(
            @ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("studentId", studentId);
            params.put("payStatus", 1);
            List<YsOrder> list = orderService.getListByMapParams(params);
            return ResultDTO.successResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "首页统计")
    @RequestMapping(value = "getHomeStatistical", method = RequestMethod.GET)
    public ResultDTO<MoneyStatistical> getHomeStatistical(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (orgId != null && orgId != 1) params.put("orgId", orgId);
            //不是管理员 查询当前机构下的列表
            if (!isSuperAdmin(userDto)){
                if (userDto.getServiceAreaIds() == null)
                    return new ResultDTO<>(ErrorCode.ROLE_PERMISSION_ERROR);
                params.put("serviceAreaIds",userDto.getServiceAreaIds());
            }
            return orderService.getHomeStatistical(params);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "订单 金额统计")
    @RequestMapping(value = "getOrderMoneyStatistical", method = RequestMethod.GET)
    public ResultDTO<MoneyStatistical> getOrderMoneyStatistical(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (orgId != null && orgId !=1) {
                params.put("orgId", orgId);
            }
            //不是管理员 查询当前机构下的列表
            if (!isSuperAdmin(userDto)){
                if (userDto.getServiceAreaIds() == null)
                    return new ResultDTO<>(ErrorCode.ROLE_PERMISSION_ERROR);
                params.put("serviceAreaIds",userDto.getServiceAreaIds());
            }
            return orderService.getOrderMoneyStatistical(params);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "经营报表（学校）分页列表")
    @RequestMapping(value = "getSchoolBusinessReportListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<OrgDto>> getSchoolBusinessReportList(
            @ApiParam(value = "学校名称（模糊搜索）", required = false) @RequestParam(name = "orgName", required = false) String orgName,
            @ApiParam(value = "开始日期", required = false) @RequestParam(name = "startDate", required = false) String startDate,
            @ApiParam(value = "截止日期", required = false) @RequestParam(name = "endDate", required = false) String endDate,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(orgName)) params.put("orgName", orgName);
            if (!StringUtil.isEmpty(startDate)) params.put("startDate", startDate);
            if (!StringUtil.isEmpty(endDate)) params.put("endDate", endDate);
            //不是管理员 查询当前机构下的列表
            if (!isSuperAdmin(userDto)){
                if (userDto.getServiceAreaIds() == null)
                    return new ResultDTO<>(ErrorCode.ROLE_PERMISSION_ERROR);
                params.put("serviceAreaIds",userDto.getServiceAreaIds());
            }
            PageInfo<OrgDto> pageInfo = orderService.getSchoolBusinessReportList(params,pageNo,pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "课程经营报表（学校经营报表详情）")
    @RequestMapping(value = "getOrgCourseBusinessReportListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<BusinessReport>> getOrgCourseBusinessReportListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "开始日期", required = false) @RequestParam(name = "startDate", required = false) String startDate,
            @ApiParam(value = "截止日期", required = false) @RequestParam(name = "endDate", required = false) String endDate,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(startDate)) params.put("startDate", startDate);
            if (!StringUtil.isEmpty(endDate)) params.put("endDate", endDate);
            if (orgId != null && orgId != 1) params.put("orgId",orgId);
            //不是管理员 查询当前机构下的列表
            if (!isSuperAdmin(userDto)){
                if (userDto.getServiceAreaIds() == null)
                    return new ResultDTO<>(ErrorCode.ROLE_PERMISSION_ERROR);
                params.put("serviceAreaIds",userDto.getServiceAreaIds());
            }
            PageInfo<BusinessReport> pageInfo = orderService.getOrgCourseBusinessReportListByPage(params,pageNo,pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "订单列表")
    @RequestMapping(value = "getOrderListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<YsOrder>> getOrderListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "商品名称（模糊搜索）", required = false) @RequestParam(name = "title", required = false) String title,
            @ApiParam(value = "学生姓名（模糊搜索）", required = false) @RequestParam(name = "stuName", required = false) String stuName,
            @ApiParam(value = "家长手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "订单类型：1课程 2托管", required = false) @RequestParam(name = "orderType", required = false) Integer orderType,
            @ApiParam(value = "支付状态：0未支付 1已支付", required = false) @RequestParam(name = "payStatus", required = false) Integer payStatus,
            @ApiParam(value = "退款状态：0用户申请退款 1已退款 2拒绝退款", required = false) @RequestParam(name = "refundStatus", required = false) Integer refundStatus,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(title)) params.put("title", title);
            if (!StringUtil.isEmpty(stuName)) params.put("stuName", stuName);
            if (!StringUtil.isEmpty(mobile)) params.put("mobile", mobile);

            //不是管理员 查询当前机构下的列表
            if (!isSuperAdmin(userDto)){
                if (userDto.getServiceAreaIds() == null)
                    return new ResultDTO<>(ErrorCode.ROLE_PERMISSION_ERROR);
                params.put("serviceAreaIds",userDto.getServiceAreaIds());
            }
            params.put("orgId", orgId);
            params.put("orderType", orderType);
            params.put("payStatus", payStatus);
            params.put("refundStatus", refundStatus);
            PageInfo<YsOrder> pageInfo = orderService.getListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "退款列表")
    @RequestMapping(value = "getRefundOrderListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<YsOrder>> getRefundOrderListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "商品名称（模糊搜索）", required = false) @RequestParam(name = "title", required = false) String title,
            @ApiParam(value = "学生姓名（模糊搜索）", required = false) @RequestParam(name = "stuName", required = false) String stuName,
            @ApiParam(value = "家长手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "订单类型：1课程 2托管", required = false) @RequestParam(name = "orderType", required = false) Integer orderType,
            @ApiParam(value = "支付状态：0未支付 1已支付", required = false) @RequestParam(name = "payStatus", required = false) Integer payStatus,
            @ApiParam(value = "退款状态：0用户申请退款 1已退款 2拒绝退款", required = false) @RequestParam(name = "refundStatus", required = false) Integer refundStatus,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (!StringUtil.isEmpty(title)) params.put("title", title);
            if (!StringUtil.isEmpty(stuName)) params.put("stuName", stuName);
            if (!StringUtil.isEmpty(mobile)) params.put("mobile", mobile);
            params.put("orgId", orgId);
            params.put("orderType", orderType);
            params.put("payStatus", payStatus);
            params.put("refund", true);
            params.put("refundStatus", refundStatus);
            //不是管理员 查询当前机构下的列表
            if (!isSuperAdmin(userDto)){
                if (userDto.getServiceAreaIds() == null)
                    return new ResultDTO<>(ErrorCode.ROLE_PERMISSION_ERROR);
                params.put("serviceAreaIds",userDto.getServiceAreaIds());
            }
            PageInfo<YsOrder> pageInfo = orderService.getListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "订单退款审核")
    @RequestMapping(value = "auditRefund", method = RequestMethod.POST)
    public ResultDTO<Boolean> auditRefund(
            @ApiParam(value = "订单号", required = false) @RequestParam(name = "orderNumber", required = true) String orderNumber,
            @ApiParam(value = "状态：1同意 2拒绝", required = false) @RequestParam(name = "refundStatus", required = true) Integer refundStatus
            ){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            YsOrder data = new YsOrder();
            data.setOrderNumber(orderNumber);
            data.setRefundStatus(refundStatus);
            data.setAuditUserId(userDto.getId());
            data.setAuditUserName(userDto.getName());
            return orderService.auditRefund(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "订单详情")
    @RequestMapping(value = "getOrderByNumber", method = RequestMethod.GET)
    public ResultDTO<YsOrder> getOrderByNumber(
            @ApiParam(value = "订单号", required = true) @RequestParam(name = "orderNumber", required = true) String orderNumber) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            YsOrder data = orderService.getOrderByNumber(orderNumber);
            return ResultDTO.successResult(data);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "删除订单")
    @RequestMapping(value = "delOrder", method = RequestMethod.POST)
    public ResultDTO<YsOrder> delOrder(
            @ApiParam(value = "订单号", required = true) @RequestParam(name = "orderNumber", required = true) String orderNumber) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            orderService.delOrder(orderNumber);
            return new ResultDTO<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

}